package com.p2p.front.web.controller;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import com.p2p.base.exception.BizException;
import com.p2p.base.model.Money;
import com.p2p.base.util.mail.JavaWebapi;
import com.p2p.base.util.mail.SendCloudMail;
import com.p2p.base.web.controller.BaseController;
import com.p2p.front.dal.model.LoanInfo;
import com.p2p.front.dal.model.Tender;
import com.p2p.front.dal.model.User;
import com.p2p.front.enums.LoanRepayMethod;
import com.p2p.front.service.LoanInfoService;
import com.p2p.front.service.LoanRepayService;
import com.p2p.front.service.TenderService;
import com.p2p.front.service.UserService;
import com.p2p.front.util.PdfDownload;
import com.p2p.front.util.RateUtil;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * leiwen@yiqihao.com
 */
@Controller
@RequestMapping("pdf")
public class LoanPdfController extends BaseController {

	@Resource
	private FreeMarkerConfig freemarkerConfig;

	@Resource
	private LoanInfoService loanInfoService;
	@Resource
	private TenderService tenderService;

	@Resource
	private UserService userService;
	@Resource
	private LoanRepayService loanRepayService;

	@RequestMapping("/loan")
	public String loanPdf(@RequestParam Long lid, Model model) {
		Map<String, Object> params = loanPdfParams(lid);
		model.addAllAttributes(params);
		return "pdf/loan_contract_pdf";
	}

	@RequestMapping("/tender")
	public String tenderPdf(@RequestParam Long tid, Model model) {
		Map<String, Object> params = tenderPdfParams(tid);
		model.addAllAttributes(params);
		return "pdf/tender_contract_pdf";
	}

	@RequestMapping("/loan/download")
	public void downloadLoanPdfFtl(@RequestParam Long lid,
			HttpServletRequest req, HttpServletResponse res) {
		Configuration configuration = this.freemarkerConfig.getConfiguration();
		Map<String, Object> params = loanPdfParams(lid);

		try {
			Template pdfTmplate = configuration
					.getTemplate("user/pdf/loan_contract_pdf.ftl");
			String htmlText = FreeMarkerTemplateUtils
					.processTemplateIntoString(pdfTmplate, params);
			Map<String, Object> post = new HashMap<String, Object>();
			post.put("content", htmlText);
			post.put("title", "loan_contract_pdf");
			PdfDownload.doDownloadPdfPost(res, post);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
	}

	private Map<String, Object> loanPdfParams(Long lid) {
		LoanInfo loan = loanInfoService.getLoanInfoById(lid);
		Map<String, Object> params = new HashMap<String, Object>();
		List<Tender> tenderList = tenderService.findSuccesedByLoanId(lid);
		if(tenderList!=null&&tenderList.size()>0){
			handlerMonthInterestOrMonthReturn(tenderList, loan);
			params.put("loan", loan);
			params.put("tenderList", tenderList);
			Tender tender = tenderList.get(0);
			Date repayDate = tender.getLoanTime();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(repayDate);
			int repayDay = calendar.get(Calendar.DAY_OF_MONTH);
			User loanUser = userService.findById(loan.getUid() + "");
			params.put("loanUser", loanUser);
			params.put("repayDay", repayDay);
		}else{
			throw new BizException("no tender", "没有人投标");
		}
		
		return params;
	}

	// 处理每个tender和这个loan的monthInterest,monthReturn,
	private void handlerMonthInterestOrMonthReturn(List<Tender> tenderList,
			LoanInfo loan) {
		String repayMethod = loan.getRepayMethod();
		if (repayMethod.equals(LoanRepayMethod.m.name())) {
			for (Tender tender : tenderList) {
				Money monthReturn = RateUtil
						.getMonthRepayAmountForPrincipalAndInterest(
								loan.getReturnApr(), loan.getDeadline(),
								tender.getReturnPrincipal());
				tender.setMonthReturn(monthReturn);
			}
		} else if (repayMethod.equals(LoanRepayMethod.i.name())) {
			for (Tender tender : tenderList) {
				Money monthInterest = RateUtil.getMonthInterestForNormal(
						loan.getReturnApr(), loan.getDeadline(),
						tender.getReturnPrincipal());
				tender.setMonthInterest(monthInterest);
			}
		}
		// 手动计算，包含rewardApr，loanVaration的不准确
		Money monthReturn = RateUtil
				.getMonthRepayAmountForPrincipalAndInterest(
						loan.getReturnApr(), loan.getDeadline(),
						loan.getAmount());
		loan.setMonthReturn(monthReturn);
		Money monthInterest = RateUtil.getMonthInterestForNormal(
				loan.getReturnApr(), loan.getDeadline(), loan.getAmount());
		loan.setMonthInterest(monthInterest);
		Money allInterest = RateUtil.getAllInterest(loan.getApr(),
				loan.getDeadline(), loan.getAmount(), repayMethod);
		Money repayAmount = new Money(allInterest.getCent()
				+ loan.getAmount().getCent());
		loan.setRepayAmount(repayAmount);
	}

	@RequestMapping("/tender/download")
	public void downloadTenderPdfFtl(@RequestParam Long tid,
			HttpServletRequest req, HttpServletResponse res) {
		Configuration configuration = this.freemarkerConfig.getConfiguration();
		Map<String, Object> params = tenderPdfParams(tid);
		try {
			Template pdfTmplate = configuration
					.getTemplate("user/pdf/tender_contract_pdf.ftl");
			String htmlText = FreeMarkerTemplateUtils
					.processTemplateIntoString(pdfTmplate, params);
			Map<String, Object> post = new HashMap<String, Object>();
			post.put("content", htmlText);
			post.put("title", "tender_contract_pdf");
			PdfDownload.doDownloadPdfPost(res, post);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}

	}

	@RequestMapping("/sendMail")
	public void testSendMail(@RequestParam Long lid,
			HttpServletRequest req, HttpServletResponse res) {
		Configuration configuration = this.freemarkerConfig.getConfiguration();
		Map<String, Object> params = loanPdfParams(lid);

		try {
			Template pdfTmplate = configuration
					.getTemplate("user/pdf/loan_contract_pdf.ftl");
			String htmlText = FreeMarkerTemplateUtils
					.processTemplateIntoString(pdfTmplate, params);
			System.out.println(htmlText);
			JavaWebapi.send("240370818@qq.com", "投标协议", htmlText);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
	}
	
	private Map<String, Object> tenderPdfParams(Long tid) {
		Map<String, Object> tender = tenderService.get(tid);
		Map<String, Object> loan = loanInfoService.get(Long.parseLong(tender
				.get("lid").toString()));
		Map<String, Object> tenderUser = userService.get(Long.parseLong(tender
				.get("uid").toString()));
		Map<String, Object> loanUser = userService.get(Long.parseLong(loan.get(
				"uid").toString()));
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("tender", tender);
		params.put("loan", loan);
		params.put("tenderUser", tenderUser);
		params.put("loanUser", loanUser);
		return params;
	}
}
